import { _decorator, Component, Graphics, Node, v3, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('TargetLine')
export class TargetLine extends Component {

    g: Graphics
    // 发射起点
    pos1:Vec3 = v3(0, 0, 0)
    // 发射终点
    pos2:Vec3 = v3(0, 0, 0)
    // 速度
    speed:number = 0

    // 每次绘制的起点
    point1:Vec3 = v3(0, 0, 0)
    // 每次绘制的终点
    point2:Vec3 = v3(0,0,0)

    start() {
        this.g = this.getComponent(Graphics)
    }

    update(deltaTime: number) {
      
        if(Vec3.distance(this.point2, this.pos2) < this.speed * deltaTime){
            this.node.destroy()
        }
        
        // Vec3.lerp(this.point2, this.point2, this.pos2, this.speed * deltaTime)
       
        let dir = this.pos2.clone().subtract(this.pos1).normalize()
        let step = dir.multiplyScalar(this.speed * deltaTime)
        this.point2 = this.point2.clone().add(step)
       
        
        this.drawLine(this.point1, this.point2)
        this.point1 = this.point2.clone()
    }

    setData(pos1: Vec3, pos2: Vec3, speed:number){
       
        this.speed = speed
        
      
        this.node.inverseTransformPoint(this.pos1, pos1)
        this.node.inverseTransformPoint(this.pos2, pos2)
        this.point1 = this.pos1.clone()
        this.point2 = this.pos1.clone()
    }

    drawLine(pos1: Vec3, pos2: Vec3) {
     
        // this.g.clear()
        this.g.moveTo(pos1.x, pos1.y);
        this.g.lineTo(pos2.x, pos2.y);
        this.g.stroke();
    }
}


